#include"include/muduo/net/TcpClient.h"
#include"include/muduo/net/EventLoopThread.h"
#include"include/muduo/net/TcpConnection.h"
#include"include/muduo/base/CountDownLatch.h"
#include<iostream>
#include<functional>

class TranslateClient
{
public:
    TranslateClient(const std::string& sip, uint16_t port)
        :_latch(1)
        ,_client(_loopthread.startLoop(), muduo::net::InetAddress(sip, port), "TranslateClient")
    {
        auto func1 = std::bind(&TranslateClient::onConnection, this, std::placeholders::_1);
        auto func2 = std::bind(&TranslateClient::onMessage, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3);
        _client.setConnectionCallback(func1);
        _client.setMessageCallback(func2);
    }
    //需要等待链接成功后再返回 阻塞等待用latch
    void connect()
    {
        _client.connect();  //会直接返回
        _latch.wait();      //阻塞等待 直到链接成功
    }
    bool send(const std::string &msg)
    {
        if(_conn->connected())
        {
            _conn->send(msg);
            return 1;
        }
        else
        {
            return false;
        }
    }
private:
    //链接建立成功的回调函数  链接建立成功后 唤醒上面的阻塞
    void onConnection(const muduo::net::TcpConnectionPtr& conn)
    {
        if(conn->connected())
        {
            _latch.countDown(); //唤醒主线程阻塞
            _conn = conn;
        }
        else
        {
            //链接关闭时的操作
            _conn.reset();
        }
    }
    //收到消息时的回调函数
    void onMessage(const muduo::net::TcpConnectionPtr& conn, muduo::net::Buffer* buf, muduo::Timestamp)
    {
        std::cout << "翻译结果：" << buf->retrieveAllAsString() << std::endl;
    }

private:
    muduo::CountDownLatch _latch;
    //因为eventloop 是阻塞式 主线程一跑就阻塞住了 需要多线程
    //muduo::net::EventLoop _baseloop; //用loopthread 内部包含baseloop
    muduo::net::EventLoopThread _loopthread;        //内部自动循环
    muduo::net::TcpClient _client;
    muduo::net::TcpConnectionPtr _conn;
};

int main()
{
    TranslateClient client("127.0.0.1", 8888);
    client.connect();

    while(1)
    {   
        std::string buf;
        std::cin >> buf;
        client.send(buf);
    }
    return 0;
}